<template>
  <a-modal :open="editOpen" title="编辑任务" width="800px" :confirm-loading="loading" @ok="ok" @cancel="cancel">
    <a-form
      ref="taskFormRef"
      :model="formState"
      :layout="'vertical'"
      :rules="taskRules"
      :label-col="{ style: { width: '120px' } }"
      label-align="left"
    >
      <!-- class="w-560" -->

      <a-form-item v-if="formState.normDetailsIdList?.length" label="评估指标" name="labelIds">
        <div class="w-704">
          <a-select
            v-model:value="formState.normDetailsIdList"
            class="w-440"
            :show-search="false"
            :options="normDetailsOptions"
            :field-names="{ label: 'name', value: 'id' }"
            mode="multiple"
            max-tag-count="responsive"
            placeholder="请选择类型"
            style="width: 100%"
            show-arrow
          />
        </div>
      </a-form-item>
      <a-form-item v-if="!formState.normDetailsIdList?.length" label="评估代码" name="codeFileUrl">
        <file-upload
          v-model:file-url="formState.codeFileUrl"
          class="file-upload w-440"
          :max-count="1"
          :is-preview="false"
          accept="zip"
          suffix="zip"
          :module-custom-prefix="prefixUrl"
          :custom-prefix-name-has-unix="false"
          :max-file-size="200"
          @upload-success-after="fileUploadSuccess"
        >
          <a-button type="dashed" size="small" class="icon-with-btn btn-mini">
            <div class="upload-btn">
              <img src="@/assets/img/upload-2-line-text02.svg" alt="" />
              上传
            </div>
          </a-button>
        </file-upload>
      </a-form-item>
      <a-form-item label="数据集" name="dataIdList">
        <div class="w-866">
          <g-select-tree-data
            ref="selectDataBucketRef"
            v-model:checked-ids="formState.dataIdList"
            type-name="数据集"
            auto-expand-parent
            :has-modal="false"
            :get-tree-data-api="selectTreeDataApi.dataBucketTree"
            :get-collect-tree-data-api="selectTreeDataApi.collectDataBucketTree"
            :get-list-data-api="selectTreeDataApi.searchBucketList"
            :get-collect-list-data-api="selectTreeDataApi.collectSearchBucketList"
            :field-names="{ children: 'children', title: 'name', key: 'id' }"
          >
            <template #selected-tools>
              <a-tooltip title="仅从已选数据集中抽取满足“数据处理规则”格式条件的文件">
                <i class="iconfont icon-information-fill text-color-4 ml-8 h-22"></i>
              </a-tooltip>
            </template>
          </g-select-tree-data>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { nextTick, ref } from 'vue'
  import { useRequest } from 'vue-request'

  import FileUpload from '@/components/upload/FileUpload/index.vue'
  import { modelEvaluationApi, selectTreeDataApi } from '@/services/api'
  import { validateBitLen, validateDirName } from '@/utils'

  interface FromState {
    normDetailsIdList?: string
    modelType: Number
    labelIds: string | number[]
    id: string
    source: string[]
    modelInfoId: string
    size: string
    codeFileUrl: string
    dataIdList: string[]
  }
  const taskFormRef = ref()
  const props = defineProps({
    open: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  })

  const editOpen = ref<boolean>(false)

  const emits = defineEmits<{ (e: 'handleOk'): void; (e: 'handleCancel'): void }>()

  let validateDataBucket = async (rule: Rule, value: string) => {
    if (value.length === 0) {
      return Promise.reject('请选择数据集')
    }
    return Promise.resolve()
  }
  const taskRules: Record<string, Rule[]> = {
    labelIds: [{ required: true, message: '请选择算法服务', trigger: 'change' }],
    dataIdList: [{ required: true, trigger: 'change', validator: validateDataBucket }],
    codeFileUrl: [{ required: true, message: '请选择算法服务', trigger: 'change' }]
  }
  const formState = ref<FromState>({
    id: '',
    normDetailsIdList: '',
    size: '',
    labelIds: [],
    modelType: 0,
    codeFileUrl: '',
    source: [],
    modelInfoId: '',
    dataIdList: []
  })

  // 文件上传前缀prefixUrl
  const prefixUrl = ref<string>('/')

  const normDetailsOptions = ref<Record<string, number | string>[]>([])
  // 初始化时获取文件前缀
  // const initFilerefixUrl = async () => {
  //   const { data } = await modelEvaluationApi.uploadDir()
  //   formState.value.id = data.taskId
  //   prefixUrl.value = data.codeFileParentDir
  // }

  const fileUploadSuccess = (file: any) => {
    formState.value.size = file.size
  }

  // 获取评估指标
  const getNormDetailsOptions = async () => {
    const { data } = await modelEvaluationApi.getNormDetailsOptions()
    normDetailsOptions.value = data
  }
  const cancel = () => {
    editOpen.value = false
  }
  const ok = () => {
    taskFormRef.value
      .validate()
      .then(() => {
        submitForm()
      })
      .catch((err: any) => {
        console.log(err)
      })
  }

  const { loading, runAsync: runAddDataCleaning } = useRequest(modelEvaluationApi.edit)

  const params = ref<any>({})

  const submitForm = async () => {
    // 模型管理
    if (formState.value.modelType === 0) {
      params.value.id = formState.value.id
      params.value.modelType = formState.value.modelType
      params.value.modelInfoId = formState.value.modelInfoId
      params.value.source = formState.value.source
      params.value.normDetailsIdList = formState.value.normDetailsIdList
      params.value.dataIdList = formState.value.dataIdList
      params.value.codeFileUrl = formState.value.codeFileUrl
    }
    // 收藏的公开模型
    if (formState.value.modelType === 1) {
      params.value.modelType = formState.value.modelType
      params.value.modelInfoId = formState.value.modelInfoId
      params.value.dataIdList = formState.value.dataIdList
      params.value.normDetailsIdList = formState.value.normDetailsIdList
    }
    try {
      await runAddDataCleaning(params.value, { isAddUid: true })

      message.success('操作成功')
      editOpen.value = false
      emits('handleOk')
    } catch (error) {
      console.log('---', error)
      if (error.code === 'ATP-100021') {
        emits('handleOk')
      }
    }
  }
  // 获取详情
  const getDetail = async (id: string): Promise<void> => {
    console.log('props.id:', id)

    const { data } = await modelEvaluationApi.getDetail({ id })
    formState.value = {
      ...data
    }
    // Object.assign(formState.value, data)
    formState.value.dataIdList = data.dataIdList.map((item: any) => {
      return {
        key: item,
        checked: true
      }
    })
    prefixUrl.value = data.path

    console.log('formState.value :', data, formState.value)
    formState.value.dataIdList.forEach((it: any) => {
      selectDataBucketRef.value?.addKey(it)
    })
    // selectDataBucketRef.value?.open()
    // await nextTick()
  }
  const selectDataBucketRef = ref()
  const openModal = (id: string) => {
    editOpen.value = true
    getNormDetailsOptions()
    getDetail(id)
    // initFilerefixUrl()
  }

  defineExpose({
    openModal
  })
</script>

<style lang="less" scoped>
  .upload-btn {
    color: @text02;

    img {
      padding-bottom: 4px;
      width: 14px;
      height: 14px;
      vertical-align: middle;
    }
  }
</style>
